// Login helper object

Ext.namespace("MyApp.common").login = new function () {
  var loginData = null;
  
  function refreshLoginData(doOnSuccess) {
    MyApp.common.sendJsonRequestAndDoOnSuccess(
      {
        url: restPath + '/js/common-login-data'
      },
      function (jsonResponse) {
        loginData = jsonResponse.data;
        
        doOnSuccess();
      }
    );
  }
  this.refreshLoginData = refreshLoginData;
  
  function checkLogin(rolesAllowed, doOnPass, doOnLoggedOut, doOnMissingRole) {
    if (typeof rolesAllowed == "undefined" || rolesAllowed == null) {
      rolesAllowed = [];
    }

    if (rolesAllowed.length > 0) {
      if(loginData.loggedIn == false) {
//        alert("redirect-replace logout-confirmation");
        doOnLoggedOut();
        return;
      }
      
      var hasRequiredRole = false;
      for(rolesAllowedCounter = 0;  hasRequiredRole == false && rolesAllowedCounter < rolesAllowed.length; rolesAllowedCounter++) {
        hasRequiredRole = isUserInRole(rolesAllowed[rolesAllowedCounter]);
      }
      
      if(hasRequiredRole == false) {
        var requiredRolesString = "";
        for(rolesAllowedCounter = 0; rolesAllowedCounter < rolesAllowed.length; rolesAllowedCounter++) {
          if(requiredRolesString != "") {
            requiredRolesString += ", ";
          }
          requiredRolesString += rolesAllowed[rolesAllowedCounter];
        }
        
//        alert("redirect-replace missing-role");
        doOnMissingRole();
        return;
      }
    }
    doOnPass();
  }
  
  function refreshLoginDataAndCheckLogin(rolesAllowed, doOnPass, doOnLoggedOut, doOnMissingRole) {
    refreshLoginData(function () {
      checkLogin(rolesAllowed, doOnPass, doOnLoggedOut, doOnMissingRole);
    });
  }
  this.refreshLoginDataAndCheckLogin = refreshLoginDataAndCheckLogin;
  
  function isUserInRole(roleToCheck) {
    return typeof loginData.hasRoles != "undefined" && Ext.Array.indexOf(loginData.hasRoles, roleToCheck) > -1;
  }
  this.isUserInRole = isUserInRole;
  
  function getLoginData() {
    return loginData;
  }
  this.getLoginData = getLoginData;
}();
